<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: [ JRK丶Admin ]
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/6/26 0026
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------

namespace app\admin\controller;


use app\common\controller\AdminBaseController;
use app\common\model\tang\BalanceLog;
use app\common\model\tang\CostRule;
use app\common\model\tang\Merchant as MerchantModel;
use app\common\model\tang\Cost as CostModel;
use app\common\model\tang\CostType;
use app\common\model\tang\SubjectList;
use think\facade\Config;
use think\facade\Db;

class Deposit extends AdminBaseController
{
    protected function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new CostModel();
    }
    public function index()
    {
        if (IS_AJAX){
            return $this->model->getAdminPageData($this->param, 'id desc',['is_user'=>0,'type'=>1]);
        }
        $merchant_list =\app\common\model\tang\Merchant::field('id,merchant_sn,name,company,username,code')->select();
        //获取菜单列表
        $this->assign(compact("merchant_list"));
        return $this->fetch();
    }

    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:人工缴费
     */
    public function adminAdd()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            if (empty($data['datas'])){
                return parent::JsonReturn('缴费项不存在', 0);
            }
            Db::startTrans();
            try {
                $model =  new \app\common\model\tang\Cost();
                if($data['merchant_type']==2){  //临时商户缴费
                    if (empty($data['merch_username'])){
                        return parent::JsonReturn('商户姓名不能为空', 0);
                    }
                    if (empty($data['merch_mobile'])){
                        return parent::JsonReturn('商户手机号码不能为空', 0);
                    }
                    // 创建新商户
                    $merchant_id = (new MerchantModel())->AddMerchant($data['merch_username'],$data['merch_mobile']);
                    if(!$merchant_id){
                        return self::JsonReturn("手机号码已被注册", 0);
                    }else{
                        $data['merchant_id'] = $merchant_id ;
                        unset($data['merch_username']);
                        unset($data['merch_mobile']);
                    }
                }
                unset($data['__token__']);
                unset($data['date']);
                unset($data['file']);
                unset($data['merchant_type']);
                $z_money = 0 ;
                $amount = 0 ;
                foreach ($data['datas'] as $v){
                    $z_money += $v['z_money'] ;
                    if($v['id']>0){
                        $amount += $v['z_money'] ;
                    }
                }
                if($z_money!=$data['real_amount']){
                    return parent::JsonReturn('订单价格错误', 0);
                }
                if((int)$z_money!=(int)$data['amount']){
                    return parent::JsonReturn('订单价格错误', 0);
                }
                $amount = intval($data['amount'] * 100) ;
                $data['unit_price'] =  $amount ;
                $data['number'] = 1 ;
                $data['amount'] = $amount;
//                $data['real_amount'] =$data['amount'];
//                $data['unit_price'] = $amount ; // 单价
//                $data['amount'] = intval($amount * 100);
//                $data['number'] = 1;  // 购买数量
                $data['service_charge'] = intval($data['service_charge'] * 100);
                $data['real_amount'] =intval($data['real_amount'] * 100);
                $data['other_certificate'] = $data['description'];
                $data['add_user'] = static::$admin_info['nickname'];
                $data['order_sn'] = OrderSn();
                $data['pay_time'] = date('Y-m-d H:i:s',time());
                $model->save($data);
                $arr = [];
                foreach ($data['datas'] as $key=>$value){
                    $arr[$key]['name'] = $value['cost_name'];
                    $arr[$key]['type'] = $value['type'];
                    $arr[$key]['unitprice'] = $value['unitprice'];
                    $arr[$key]['money'] = $value['money'];
                    $arr[$key]['z_money'] = $value['z_money'];
                    $arr[$key]['cost_sn'] = $value['cost_sn'];
                    $arr[$key]['tax_sn'] = $value['tax_sn'];
                    $arr[$key]['tax_money'] = $value['tax_money'];
                    $arr[$key]['cost_type_id'] = $value['id'];
                    $arr[$key]['tax_rate'] = $value['tax_rate'];
                    $arr[$key]['pid'] = $model->id;
                    $arr[$key]['create_time'] = time();
                }
                (new CostRule())->insertAll($arr);
                Db::commit();
                return self::JsonReturn("添加成功");
            }catch (\Exception $exception){
                Db::rollback();
                return self::JsonReturn($exception->getMessage(),0);
            }
        }
        $merchant_list = (new MerchantModel())->where('status' ,'<>',-1)->field('id,merchant_sn,name,company')->select();
        $cost_type_list = (new CostType())
            ->where('type','=',1)
            ->where('pid','=',0)
            ->field('id,cost_name')->select();
        $pay_type = (new SubjectList())->where('type','=',1)->field('id,name')->select();
        $id = $this->request->param("id/d");//父id
        $info = $this->model->find($id);
        //所属部门
        $department_list = SubjectList::where('type','=',2)->field('id,name')->select();
        //获取菜单列表
        $this->assign(compact("info", "id","merchant_list","cost_type_list","department_list","pay_type"));
        return $this->fetch();
    }

    public function getCostType()
    {
        $param = $this->request->param();
        $cost_type    = intval($param['cost_type']);
        $amount      = $param['amount'];  //  金额
        if($amount<=0){
            return self::ajaxResult([],0,1,'缴费金额不合法');
        }
        if(!empty($param['service_charge_rate'])){
            $service_charge_rate = $param['service_charge_rate'];  //  手续费  %
        }
        $cost_type_list = (new CostType())->where('pid','=',$cost_type)->field('id,type,cost_name,cost_sn,tax_sn,tax_rate,tax,cost_money,th_money')->select()->toArray();
        if (empty($cost_type)){
            return self::ajaxResult([],0,1,'缴费类型不存在');
        }
        $return = [] ;
        if(!empty($cost_type_list)){
            $k = 0 ;
            $data = [] ;
//            $amount = 0 ;
            foreach ($cost_type_list as  $v){
                $k++ ;
                $data[] = [
                    'id'        => $v['id'],
                    'cost_name' => $v['cost_name'],
                    'type'      => $v['type'],
                    'cost_sn'   => $v['cost_sn'], // 收费科目
                    'tax_sn'    => $v['tax_sn'],  // 税率科目
                    'unitprice' => $amount , // 税率
                    'tax_rate'  => $v['tax_rate'] ,  // 税率
                    'tax_money' => 0, // 税率金额
                    'money'     => $amount, // 收入金额
                    'z_money'   => $amount,  // 总金额
                ];
//                $amount +=$v['cost_money'] ;
            }
            if(!empty($service_charge_rate)){
                $service_charge_money = round($amount * $service_charge_rate,2);
                $data[$k] = [
                    'id'        => 0,
                    'cost_name' => '手续费',
                    'type'      => '2',
                    'cost_sn'   =>  '',
                    'tax_sn'    =>  '',
                    'unitprice' => 0,
                    'tax_rate'  => 0,  // 税率
                    'tax_money' => 0, // 税率金额
                    'money'     => $service_charge_money, // 收入金额
                    'z_money'   => $service_charge_money,  // 总金额
                ];
            }
            $service_charge_money = !empty($service_charge_money) ? $service_charge_money:0 ;
            $z_reality_money = round($service_charge_money + $amount ,2);
            $return = [
                'data'     => $data,
                'service_charge_money'  => $service_charge_money,
                'z_money'  => $z_reality_money
            ];
        }
        return self::ajaxResult($return,0,0,'success');
    }

    public function ServiceCharge()
    {
        $id = $this->request->param("id/d");//父id
        if (empty($id)){
            return self::ajaxResult([],0,1,'fail');
        }
        $service_charge = (\app\common\model\tang\SubjectList::where(['id'=>$id])->value('rate'))/100;
        return self::ajaxResult(['service_charge'=>$service_charge],0,0,'success');
    }

    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/6/30 0030
     * @describe:添加编辑
     */
    public function add()
    {
        if (IS_AJAX) {
            $data = $this->request->post();
            if (empty($data['datas'])){
                return parent::JsonReturn('缴费项不存在', 0);
            }
            Db::startTrans();
            try {
                $model =  new \app\common\model\tang\Cost();
                if($data['merchant_type']==2){  //临时商户缴费
                    if (empty($data['merch_username'])){
                        return parent::JsonReturn('商户姓名不能为空', 0);
                    }
                    if (empty($data['merch_mobile'])){
                        return parent::JsonReturn('商户手机号码不能为空', 0);
                    }
                    // 创建新商户
                    $merchant_id = (new MerchantModel())->AddMerchant($data['merch_username'],$data['merch_mobile']);
                    if(!$merchant_id){
                        return self::JsonReturn("手机号码已被注册", 0);
                    }else{
                        $data['merchant_id'] = $merchant_id ;
                        unset($data['merch_username']);
                        unset($data['merch_mobile']);
                    }
                }
                unset($data['__token__']);
                unset($data['date']);
                unset($data['file']);
                unset($data['merchant_type']);
                $z_money = 0 ;
                foreach ($data['datas'] as $v){
                    $z_money += $v['z_money'] ;
                }
                if((int)$z_money!=(int)$data['amount']){
                    return parent::JsonReturn('订单价格错误', 0);
                }
                $amount = intval($data['amount'] * 100) ;
                $data['unit_price'] =  $amount ;
                $data['number'] = 1 ;
                $data['amount'] = $amount;
                $data['real_amount'] =$amount;
//                $data['unit_price'] =  $data['amount'] ;
//                $data['number'] = 1 ;
//                $data['amount'] = $data['amount'];
//                $data['real_amount'] =$data['amount'];
                $data['add_user'] = static::$admin_info['nickname'];
                $data['order_sn'] = OrderSn();
                $model->save($data);
                $arr = [];
                foreach ($data['datas'] as $key=>$value){
                    $arr[$key]['name'] = $value['cost_name'];
                    $arr[$key]['type'] = $value['type'];
                    $arr[$key]['unitprice'] = $value['unitprice'];
                    $arr[$key]['money'] = $value['money'];
                    $arr[$key]['z_money'] = $value['z_money'];
                    $arr[$key]['cost_sn'] = $value['cost_sn'];
                    $arr[$key]['tax_sn'] = $value['tax_sn'];
                    $arr[$key]['tax_money'] = $value['tax_money'];
                    $arr[$key]['cost_type_id'] = $value['id'];
                    $arr[$key]['tax_rate'] = $value['tax_rate'];
                    $arr[$key]['pid'] = $model->id;
                    $arr[$key]['create_time'] = time();
                }
                (new CostRule())->insertAll($arr);
                Db::commit();
                return self::JsonReturn("添加成功");
            }catch (\Exception $exception){
                Db::rollback();
                return self::JsonReturn($exception->getMessage(),0);
            }
        }
        $merchant_list = (new MerchantModel())->where('status' ,'<>',-1)->field('id,merchant_sn,name,company')->select();

        $cost_type_list = (new CostType())
            ->where('type','=',1)
            ->where('pid','=',0)
            ->field('id,cost_name')->select();
        $id = $this->request->param("id/d");//父id
        $service_charge = (\app\common\model\tang\SubjectList::where(['type'=>1])->value('rate'))/100;
        $info = $this->model->find($id);
        // 部门
        $department_list = SubjectList::where('type','=',2)->field('id,name')->select();
        //获取菜单列表
        $this->assign(compact("info", "id","merchant_list","department_list","cost_type_list","service_charge"));
        return $this->fetch();
    }

//    public function detail()
//    {
//        $id = $this->request->param("id/d");//父id
////        $info = $this->model->with(['costRule','merchants','costType'])->find($id);
//        $info = $this->model->with(['Cost','costRule','merchants','costType'])->find($id);
//        $info->time = date('Y-m-d H:i:s',$info->create_time);
//        switch ($info->is_admin_create){
//            case 0 :
//                $info->is_user = '自主缴费';
//                $info->fees_user = $info->merchant->name;
//                break ;
//            case 1 :
//                $info->is_user = '后台缴费';
//                $info->fees_user = $info->add_user;
//                break ;
//        }
//        if(empty($info->add_user)){
//            $info->add_user = $info->merchant->name;
//        }
//        switch ($info->pay_status){
//            case -1 :
//                $info->pay_status_name = '退费';
//                break ;
//            case 0 :
//                $info->pay_status_name = '未支付';
//                break ;
//            case 1 :
//                $info->pay_status_name = '已支付';
//                break ;
//        }
//        $Subjectinfo = (new SubjectList())->where('id','=',$info->subject_id)->field('name')->find();
//        $info->subject_id = $Subjectinfo['name'] ;
//        $this->assign(compact("info", "id"));
//        return $this->fetch();
//    }

    public function detail()
    {
        $id = $this->request->param("id/d");//父id
//        $info = $this->model->with('Cost')->find($id);
        $info = $this->model->with(['Cost','costRule','merchants','costType'])->find($id);
        if($info->pay_status==0){
            $info->is_user = '未缴费';
            $info->fees_user = '未缴费';
        }else{
            switch ($info->is_user){
                case 0 :
                    $info->is_user =  '后台缴费';
                    $info->fees_user = $info->merchant->username;
                    break ;
                case 1 :
                    $info->is_user = '自主缴费';
                    $info->fees_user = $info->merchant->username;
                    break ;
            }
        }
        if(empty($info->add_user)){
            $info->add_user = $info->merchant->username;
        }
        switch ($info->pay_status){
            case -1 :
                $info->pay_status_name = '退费';
                break ;
            case 0 :
                $info->pay_status_name = '未支付';
                break ;
            case 1 :
                $info->pay_status_name = '已支付';
                break ;
        }
        if(!empty($info->costRule)){
            foreach ($info->costRule as&$v){
                switch ($v['type']){
                    case 1 :
                        $v['type'] = '押金';
                        break ;
                    case 2 :
                        $v['type'] = '费用';
                        break ;
                    case 3 :
                        $v['type'] = '证件';
                        break ;
                }
            }
        }
        $info->time = date('Y-m-d H:i:s',$info->create_time);
        $Subjectinfo = (new SubjectList())->where('id','=',$info->subject_id)->field('name')->find();
        $info->subject_id = $Subjectinfo['name'] ;
        $this->assign(compact("info", "id"));
        return $this->fetch();
    }
    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/7/12 0030
     * @describe:检测是否有需要退还的押金
     */
    public function IsRebate(){
        if (IS_AJAX) {
            $id = $this->request->param("id/d");
            $info = $this->model->with(['costRule'])->find($id);
            if($info->pay_status!=1){
                return parent::JsonReturn('订单不能退款', 1);
            }
            $arr = [] ;
            if(!empty($info->costRule)){
                foreach ($info->costRule as $v){
                    if($v['type']==1){
                        $arr[] = $v ;
                    }
                }
                if(empty($arr)){
                    return parent::JsonReturn('没有可退款的项目', 1);
                }else{
                    return self::ajaxResult($arr,0,0,'success');
                }
            }else{
                return parent::JsonReturn('没有可退款的项目', 1);
            }

        }
    }
    /**
     * @return mixed|string|\think\response\Json
     * @throws \think\db\exception\DbException
     * @author: Hhy <jackhhy520@qq.com>
     * @date: 2020/7/12 0030
     * @describe:退还押金
     */
    public function rebate(){
        if (IS_AJAX) {
            $data = $this->request->post();
            $info = $this->model->with(['merchants'])->find($data['id']);
            if($info){
                $remark = $data['remark'] ;
                $type = $data['type'] ; // 1 冲入余额
                if($info->pay_status!=1){
                    return parent::JsonReturn('订单未支付或已退款', 1);
                }
                Db::startTrans();
                try {
                    if($type==1){
                        $total = 0 ;
                        foreach ($info->costRule as& $v){
                            if($v['type']==1){
                                $total+= $v['z_money'] ;
                            }
                        }
                        $model = new BalanceLog() ;
                        $model->merchant_id = $info->merchant_id;
                        $model->status = 1;
                        $model->is_top_up = 3 ;  // 退押金
                        $model->order_sn = $info->order_sn;
                        $model->edit = 1;
                        $model->amount =  $total*100;
                        $model->remark = $remark;
                        $model->create_time = time();
                        $model->save();
                    }
                    $this->model->update(['pay_status'=>-1,'remark'=>$remark],['id'=>$data['id']]);
                    Db::commit();
                    return self::JsonReturn("退款成功");
                }catch (\Exception $exception){
                    Db::rollback();
                    return self::JsonReturn($exception->getMessage(),0);
                }
            }else{
                return parent::JsonReturn('退款订单不存在', 1);
            }
        }
        $id = $this->request->param("id/d");
        $info = $this->model->with(['costRule'])->find($id);
        $arr = [] ;
        $total = 0 ;
        foreach ($info->costRule as& $v){
            if($v['type']==1){
                $v['type'] = '押金' ;
                $arr[] = $v ;
                $total+= $v['z_money'] ;
            }
        }
        $this->assign(compact("info", "id","arr","total"));
        return $this->fetch();
    }
}